using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.Windows.Markup;
/*
 * 源码已托管：https://gitee.com/dlgcy/WPFTemplate
 */
namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [多值转换器] 连接字符串;
	/// https://bbs.csdn.net/topics/390267668?list=1194969
	/// </summary>
	/// <example>
	/// <![CDATA[
	/// <MultiBinding Converter="{local:JoinStringsConverter ','}">
	///     <Binding Path="Text" ElementName="input" />
	///     <Binding Path="Text" ElementName="input2" />
	/// </MultiBinding>
	/// ]]>
	/// </example>
	public class JoinStringsConverter : MarkupExtension, IMultiValueConverter
	{
		/// <summary>
		/// 连接字符
		/// </summary>
		public string Separator { get; set; }

		/// <summary>
		/// 是否忽略空项（默认 true-忽略）
		/// </summary>
		public bool IsIgnoreEmptyItem { get; set; } = true;

		public JoinStringsConverter()
		{
		}

		public JoinStringsConverter(string separator)
		{
			Separator = separator;
		}

		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			string[] items = values.Select(x => x + "").ToArray();
			if(IsIgnoreEmptyItem)
			{
				items = items.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
			}

			return string.Join(Separator ?? "", items);
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			return this;
		}
	}
}
